const Koa = require('koa');
const Router = require('koa-router');
const multer = require('@koa/multer');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cors = require('@koa/cors');

const app = new Koa();
const router = new Router();
const upload = multer({ dest: 'uploads/' });
app.use(cors());
const uploadedChunks = {}; // 存储已上传的切片状态


router.post('/api/upload', upload.single('file'), async (ctx) => {
  const { index, md5 } = ctx.request.body;

  // 创建存储目录
  if (!fs.existsSync(`uploads/${md5}`)) {
    fs.mkdirSync(`uploads/${md5}`);
  }

  // 移动文件到对应目录
  const tempPath = path.join(__dirname, ctx.file.path);
  const targetPath = path.join(__dirname, `uploads/${md5}/${index}`);
  fs.renameSync(tempPath, targetPath);

  // 记录已上传的切片
  if (!uploadedChunks[md5]) {
    uploadedChunks[md5] = new Set();
  }
  uploadedChunks[md5].add(parseInt(index));

  ctx.body = { success: true };
});

router.get('/api/uploaded-chunks', async (ctx) => {
    const { md5 } = ctx.query;
    // 返回已上传的切片，比如从数据库或文件系统中获取
    const uploadedChunks = await getUploadedChunks(md5); // 自定义函数
    ctx.body = uploadedChunks; // 返回一个数组，例如 [0, 1]
  });

router.post('/api/merge', async (ctx) => {
  const { md5, totalChunks } = ctx.request.body;
  const targetPath = path.join(__dirname, `uploads/${md5}.completed`);

  const writeStream = fs.createWriteStream(targetPath);
  for (let i = 0; i < totalChunks; i++) {
    const chunkPath = path.join(__dirname, `uploads/${md5}/${i}`);
    const data = fs.readFileSync(chunkPath);
    writeStream.write(data);
  }
  writeStream.end();

  // 清理已完成的切片
  fs.rmdirSync(path.join(__dirname, `uploads/${md5}`), { recursive: true });

  ctx.body = { success: true };
});

app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
  console.log('http://localhost:3000');
});